﻿Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.ComponentModel.Design.Serialization
Imports System.Drawing
Imports System.Runtime.CompilerServices
Imports System.Windows.Forms
Imports System.Workflow.ComponentModel
Imports System.Workflow.ComponentModel.Serialization

Namespace System.Workflow.ComponentModel.Design
    <DesignerSerializer(GetType(FreeformActivityDesignerLayoutSerializer), GetType(WorkflowMarkupSerializer))> _
    Public Class FreeformActivityDesigner
        Inherits CompositeActivityDesigner
        ' Events
        Public Custom Event ConnectorAdded As ConnectorEventHandler
        Public Custom Event ConnectorChanged As ConnectorEventHandler
        Public Custom Event ConnectorRemoved As ConnectorEventHandler

        ' Methods
        Public Function AddConnector(ByVal source As ConnectionPoint, ByVal target As ConnectionPoint) As Connector
            If (source Is Nothing) Then
                Throw New ArgumentNullException("source")
            End If
            If (source.AssociatedDesigner Is Nothing) Then
                Throw New ArgumentException("source", SR.GetString("Error_AssociatedDesignerMissing"))
            End If
            If (target Is Nothing) Then
                Throw New ArgumentNullException("target")
            End If
            If (target.AssociatedDesigner Is Nothing) Then
                Throw New ArgumentException("target", SR.GetString("Error_AssociatedDesignerMissing"))
            End If
            Dim connectorContainer As FreeformActivityDesigner = ConnectionManager.GetConnectorContainer(source.AssociatedDesigner)
            If (Not Me Is connectorContainer) Then
                Throw New InvalidOperationException(DR.GetString("Error_AddConnector1", New Object(0  - 1) {}))
            End If
            If (((Not MyBase.Activity Is source.AssociatedDesigner.Activity) AndAlso Not Helpers.IsChildActivity([TryCast](MyBase.Activity,CompositeActivity), source.AssociatedDesigner.Activity)) OrElse ((Not MyBase.Activity Is target.AssociatedDesigner.Activity) AndAlso Not Helpers.IsChildActivity([TryCast](MyBase.Activity,CompositeActivity), target.AssociatedDesigner.Activity))) Then
                Throw New ArgumentException(DR.GetString("Error_AddConnector2", New Object(0  - 1) {}))
            End If
            Dim item As Connector = Me.CreateConnector(source, target)
            If (Not item Is Nothing) Then
                If Me.connectors.Contains(item) Then
                    Throw New InvalidOperationException(DR.GetString("Error_AddConnector3", New Object(0  - 1) {}))
                End If
                Me.connectors.Add(item)
                item.SetParent(Me)
                Me.OnConnectorAdded(New ConnectorEventArgs(item))
            End If
            MyBase.PerformLayout
            Return item
        End Function

        Public Sub BringToFront(ByVal containedDesigner As ActivityDesigner)
            If (containedDesigner Is Nothing) Then
                Throw New ArgumentNullException("containedDesigner")
            End If
            If Not Me.ContainedDesigners.Contains(containedDesigner) Then
                Throw New ArgumentException(DR.GetString("InvalidDesignerSpecified", New Object() { "containedDesigner" }))
            End If
            Me.UpdateZOrder(containedDesigner, ZOrder.Foreground)
        End Sub

        Protected Friend Overridable Function CanConnectContainedDesigners(ByVal source As ConnectionPoint, ByVal target As ConnectionPoint) As Boolean
            Return (DirectCast(source.AssociatedDesigner, IConnectableDesigner).CanConnect(source, target) AndAlso DirectCast(target.AssociatedDesigner, IConnectableDesigner).CanConnect(source, target))
        End Function

        Protected Friend Overridable Function CanResizeContainedDesigner(ByVal containedDesigner As ActivityDesigner) As Boolean
            Return TypeOf containedDesigner Is FreeformActivityDesigner
        End Function

        Friend Function CanUpdateZOrder(ByVal activityDesigner As ActivityDesigner, ByVal zorder As ZOrder) As Boolean
            Dim parentDesigner As CompositeActivityDesigner = Me
            Dim designer2 As ActivityDesigner = activityDesigner
            Do While ((Not parentDesigner Is Nothing) AndAlso (Not designer2 Is Nothing))
                If TypeOf parentDesigner Is FreeformActivityDesigner Then
                    Dim containedDesigners As ReadOnlyCollection([Of] ActivityDesigner) = parentDesigner.ContainedDesigners
                    If ((containedDesigners.Count > 1) AndAlso (Not containedDesigners.Item(If((zorder = ZOrder.Background), 0, (containedDesigners.Count - 1))) Is designer2)) Then
                        Return True
                    End If
                End If
                designer2 = parentDesigner
                parentDesigner = parentDesigner.ParentDesigner
            Loop
            Return False
        End Function

        Protected Friend Overridable Function CreateConnector(ByVal source As ConnectionPoint, ByVal target As ConnectionPoint) As Connector
            Return New Connector(source, target)
        End Function

        Protected Overrides Sub Dispose(ByVal disposing As Boolean)
            Dim i As Integer
            For i = 0 To Me.connectors.Count - 1
                Me.connectors.Item(i).Dispose
            Next i
            Me.connectors.Clear
            MyBase.Dispose(disposing)
        End Sub

        Private Sub EnsureDesignerExtender()
            Dim flag As Boolean = True
            Dim service As IExtenderListService = [TryCast](MyBase.GetService(GetType(IExtenderListService)),IExtenderListService)
            If (Not service Is Nothing) Then
                Dim provider As IExtenderProvider
                For Each provider In service.GetExtenderProviders
                    If (provider.GetType Is GetType(FreeFormDesignerPropertyExtender)) Then
                        flag = False
                        Exit For
                    End If
                Next
            End If
            If flag Then
                Dim service2 As IExtenderProviderService = [TryCast](MyBase.GetService(GetType(IExtenderProviderService)),IExtenderProviderService)
                If (Not service2 Is Nothing) Then
                    service2.AddExtenderProvider(New FreeFormDesignerPropertyExtender)
                    TypeDescriptor.Refresh(MyBase.Activity)
                End If
            End If
        End Sub

        Private Function GetEnclosingRectangle() As Rectangle
            Dim point As New Point(&H7FFFFFFF, &H7FFFFFFF)
            Dim point2 As New Point(-2147483648, -2147483648)
            Dim designer As ActivityDesigner
            For Each designer In Me.ContainedDesigners
                If designer.IsVisible Then
                    point.X = If((designer.Bounds.Left < point.X), designer.Bounds.Left, point.X)
                    point.Y = If((designer.Bounds.Top < point.Y), designer.Bounds.Top, point.Y)
                    point2.X = If((point2.X < designer.Bounds.Right), designer.Bounds.Right, point2.X)
                    point2.Y = If((point2.Y < designer.Bounds.Bottom), designer.Bounds.Bottom, point2.Y)
                End If
            Next
            If (Me.InvokingDesigner Is Nothing) Then
                Dim connector As Connector
                For Each connector In Me.Connectors
                    point.X = If((connector.Bounds.Left < point.X), connector.Bounds.Left, point.X)
                    point.Y = If((connector.Bounds.Top < point.Y), connector.Bounds.Top, point.Y)
                    point2.X = If((point2.X < connector.Bounds.Right), connector.Bounds.Right, point2.X)
                    point2.Y = If((point2.Y < connector.Bounds.Bottom), connector.Bounds.Bottom, point2.Y)
                Next
            End If
            Dim empty As Rectangle = Rectangle.Empty
            If ((point.X <> &H7FFFFFFF) AndAlso (point2.X <> -2147483648)) Then
                empty.X = point.X
                empty.Width = (point2.X - point.X)
            End If
            If ((point.Y <> &H7FFFFFFF) AndAlso (point2.Y <> -2147483648)) Then
                empty.Y = point.Y
                empty.Height = (point2.Y - point.Y)
            End If
            If Not empty.IsEmpty Then
                empty.Inflate(Me.AutoSizeMargin)
            End If
            Return empty
        End Function

        Public Overrides Function GetNextSelectableObject(ByVal current As Object, ByVal navigate As DesignerNavigationDirection) As Object
            Dim activity As Object = Nothing
            Dim list As New ArrayList(Me.ContainedDesigners)
            Dim designer As ActivityDesigner = If(TypeOf current Is Activity, ActivityDesigner.GetDesigner([TryCast](current,Activity)), ActivityDesigner.GetParentDesigner(current))
            Dim num As Integer = If((Not designer Is Nothing), list.IndexOf(designer), -1)
            If (((navigate = DesignerNavigationDirection.Left) OrElse (navigate = DesignerNavigationDirection.Up)) AndAlso ((num >= 0) AndAlso (num < list.Count))) Then
                Return DirectCast(list.Item(If((num > 0), (num - 1), (list.Count - 1))), ActivityDesigner).Activity
            End If
            If (((navigate = DesignerNavigationDirection.Right) OrElse (navigate = DesignerNavigationDirection.Down)) AndAlso (num <= (list.Count - 1))) Then
                activity = DirectCast(list.Item(If((num < (list.Count - 1)), (num + 1), 0)), ActivityDesigner).Activity
            End If
            Return activity
        End Function

        Public Overrides Function HitTest(ByVal point As Point) As HitTestInfo
            Dim info As HitTestInfo = MyBase.HitTest(point)
            Dim containedDesigners As ReadOnlyCollection([Of] ActivityDesigner) = Me.ContainedDesigners
            Dim parentView As WorkflowView = MyBase.ParentView
            Dim service As DragDropManager = [TryCast](MyBase.GetService(GetType(DragDropManager)),DragDropManager)
            If ((((Not parentView Is Nothing) AndAlso (Not service Is Nothing)) AndAlso (parentView.DragDropInProgress AndAlso (Not info.AssociatedDesigner Is Nothing))) AndAlso (service.DraggedActivities.Contains(info.AssociatedDesigner.Activity) AndAlso info.AssociatedDesigner.Bounds.Contains(point))) Then
                If (MyBase.Activity Is info.AssociatedDesigner.Activity) Then
                    Return HitTestInfo.Nowhere
                End If
                If containedDesigners.Contains(info.AssociatedDesigner) Then
                    Return New HitTestInfo(Me, HitTestLocations.Designer)
                End If
            End If
            If (Not TypeOf info Is ConnectionPointHitTestInfo AndAlso (((info.HitLocation = HitTestLocations.None) OrElse (info.AssociatedDesigner Is Me)) OrElse Me.ShowConnectorsInForeground)) Then
                Dim i As Integer
                For i = 0 To Me.connectors.Count - 1
                    If Me.connectors.Item(i).HitTest(point) Then
                        Return New ConnectorHitTestInfo(Me, (HitTestLocations.Connector Or HitTestLocations.Designer), i)
                    End If
                Next i
            End If
            Return info
        End Function

        Protected Overrides Sub Initialize(ByVal activity As Activity)
            MyBase.Initialize(activity)
            Me.EnsureDesignerExtender
        End Sub

        Public Overrides Sub InsertActivities(ByVal insertLocation As HitTestInfo, ByVal activitiesToInsert As ReadOnlyCollection([Of] Activity))
            MyBase.InsertActivities(insertLocation, activitiesToInsert)
            If Me.AutoSize Then
                Dim autoSizeMargin As Size = Me.AutoSizeMargin
                Dim location As Point = Me.Location
                Dim activity As Activity
                For Each activity In activitiesToInsert
                    Dim designer As ActivityDesigner = ActivityDesigner.GetDesigner(activity)
                    If designer.Location.IsEmpty Then
                        designer.Location = New Point((location.X + autoSizeMargin.Width), (location.Y + autoSizeMargin.Height))
                    End If
                Next
            End If
        End Sub

        Public Overrides Sub MoveActivities(ByVal moveLocation As HitTestInfo, ByVal activitiesToMove As ReadOnlyCollection([Of] Activity))
            If (moveLocation Is Nothing) Then
                Throw New ArgumentNullException("moveLocation")
            End If
            If (activitiesToMove Is Nothing) Then
                Throw New ArgumentNullException("activitiesToMove")
            End If
            Dim connectorContainer As FreeformActivityDesigner = ConnectionManager.GetConnectorContainer(Me)
            Try 
                connectorContainer.MovingActivities.Clear
                If ((Not connectorContainer Is Nothing) AndAlso (connectorContainer.Connectors.Count > 0)) Then
                    Dim activity As Activity
                    For Each activity In activitiesToMove
                        Dim designer As ActivityDesigner = ActivityDesigner.GetDesigner(activity)
                        If (ConnectionManager.GetConnectorContainer(designer) Is connectorContainer) Then
                            connectorContainer.MovingActivities.Add(designer)
                        End If
                    Next
                End If
                MyBase.MoveActivities(moveLocation, activitiesToMove)
            Finally
                connectorContainer.MovingActivities.Clear
            End Try
        End Sub

        Public Sub MoveContainedDesigner(ByVal containedDesigner As ActivityDesigner, ByVal newLocation As Point)
            If (containedDesigner Is Nothing) Then
                Throw New ArgumentNullException("containedDesigner")
            End If
            If Not Me.ContainedDesigners.Contains(containedDesigner) Then
                Throw New ArgumentException(DR.GetString("InvalidDesignerSpecified", New Object() { "containedDesigner" }))
            End If
            FreeformActivityDesigner.SetDesignerBounds(containedDesigner, New Rectangle(newLocation, containedDesigner.Size))
            MyBase.PerformLayout
            MyBase.Invalidate
        End Sub

        Protected Overridable Sub OnConnectorAdded(ByVal e As ConnectorEventArgs)
            If (Not Me.ConnectorAdded Is Nothing) Then
                Me.ConnectorAdded.Invoke(Me, e)
            End If
        End Sub

        Protected Friend Overridable Sub OnConnectorChanged(ByVal e As ConnectorEventArgs)
            If (Not Me.ConnectorChanged Is Nothing) Then
                Me.ConnectorChanged.Invoke(Me, e)
            End If
        End Sub

        Protected Overridable Sub OnConnectorRemoved(ByVal e As ConnectorEventArgs)
            If (Not Me.ConnectorRemoved Is Nothing) Then
                Me.ConnectorRemoved.Invoke(Me, e)
            End If
        End Sub

        Protected Overrides Sub OnContainedActivitiesChanging(ByVal listChangeArgs As ActivityCollectionChangeEventArgs)
            MyBase.OnContainedActivitiesChanging(listChangeArgs)
            If (listChangeArgs.Action = ActivityCollectionChangeAction.Remove) Then
                Dim connectorContainer As FreeformActivityDesigner = ConnectionManager.GetConnectorContainer(Me)
                Dim list As New List([Of] Connector)
                Dim designer2 As ActivityDesigner = Me
                Do While (Not designer2 Is Nothing)
                    Dim designer3 As FreeformActivityDesigner = [TryCast](designer2,FreeformActivityDesigner)
                    If ((Not designer3 Is Nothing) AndAlso (designer3.Connectors.Count > 0)) Then
                    Label_00CC:
                        Dim activity As Activity
                        For Each activity In listChangeArgs.RemovedItems
                            Dim designer As ActivityDesigner = ActivityDesigner.GetDesigner(activity)
                            If Not connectorContainer.MovingActivities.Contains(designer) Then
                                Dim connector As Connector
                                For Each connector In designer3.Connectors
                                    If ((designer Is connector.Source.AssociatedDesigner) OrElse (designer Is connector.Target.AssociatedDesigner)) Then
                                        list.Add(connector)
                                    End If
                                Next
                                goto Label_00CC
                            End If
                        Next
                    End If
                    designer2 = designer2.ParentDesigner
                Loop
                Dim connector2 As Connector
                For Each connector2 In list
                    connector2.ParentDesigner.RemoveConnector(connector2)
                    DirectCast(connector2, IDisposable).Dispose
                Next
            End If
        End Sub

        Protected Friend Overridable Sub OnContainedDesignersConnected(ByVal source As ConnectionPoint, ByVal target As ConnectionPoint)
            DirectCast(source.AssociatedDesigner, IConnectableDesigner).OnConnected(source, target)
            DirectCast(target.AssociatedDesigner, IConnectableDesigner).OnConnected(source, target)
        End Sub

        Protected Overrides Sub OnDragDrop(ByVal e As ActivityDragEventArgs)
            If (((e.KeyState And 8) = 8) AndAlso ((e.AllowedEffect And DragDropEffects.Copy) = DragDropEffects.Copy)) Then
                e.Effect = DragDropEffects.Copy
            ElseIf ((e.AllowedEffect And DragDropEffects.Move) = DragDropEffects.Move) Then
                e.Effect = DragDropEffects.Move
            End If
            Dim list As New List([Of] Activity)
            Dim list2 As New List([Of] Activity)
            Dim activity As Activity
            For Each activity In e.Activities
                If ((activity.Site Is Nothing) OrElse (Not activity.Parent Is MyBase.Activity)) Then
                    list.Add(activity)
                End If
                If (activity.Site Is Nothing) Then
                    list2.Add(activity)
                End If
            Next
            If (list.Count > 0) Then
                CompositeActivityDesigner.InsertActivities(Me, New ConnectorHitTestInfo(Me, HitTestLocations.Designer, DirectCast(MyBase.Activity, CompositeActivity).Activities.Count), list.AsReadOnly, SR.GetString("DragDropActivities"))
            End If
            Dim endPoint As New Point(e.X, e.Y)
            Dim pointArray As Point() = FreeFormDragDropManager.GetDesignerLocations(e.DragInitiationPoint, endPoint, e.Activities)
            If (pointArray.Length = e.Activities.Count) Then
                Dim i As Integer
                For i = 0 To e.Activities.Count - 1
                    Dim containedDesigner As ActivityDesigner = ActivityDesigner.GetDesigner(e.Activities.Item(i))
                    If (Not containedDesigner Is Nothing) Then
                        Dim newLocation As Point = If(list2.Contains(containedDesigner.Activity), endPoint, pointArray(i))
                        Me.MoveContainedDesigner(containedDesigner, newLocation)
                    End If
                Next i
            End If
        End Sub

        Protected Overrides Sub OnDragOver(ByVal e As ActivityDragEventArgs)
            If (((e.KeyState And 8) = 8) AndAlso ((e.AllowedEffect And DragDropEffects.Copy) = DragDropEffects.Copy)) Then
                e.Effect = DragDropEffects.Copy
            ElseIf ((e.AllowedEffect And DragDropEffects.Move) = DragDropEffects.Move) Then
                e.Effect = DragDropEffects.Move
            End If
        End Sub

        Protected Overrides Sub OnKeyDown(ByVal e As KeyEventArgs)
            If (e Is Nothing) Then
                Throw New ArgumentNullException("e")
            End If
            Dim service As ISelectionService = [TryCast](MyBase.GetService(GetType(ISelectionService)),ISelectionService)
            If (Not If((Not service Is Nothing), service.PrimarySelection, Nothing) Is Nothing) Then
                Dim list As New List([Of] Activity)(Helpers.GetTopLevelActivities(service.GetSelectedComponents))
                If (((e.KeyCode = Keys.Left) OrElse (e.KeyCode = Keys.Right)) OrElse ((e.KeyCode = Keys.Up) OrElse (e.KeyCode = Keys.Down))) Then
                    Dim empty As Size = Size.Empty
                    If (e.KeyCode = Keys.Left) Then
                        empty = New Size(-5, 0)
                    ElseIf (e.KeyCode = Keys.Right) Then
                        empty = New Size(5, 0)
                    ElseIf (e.KeyCode = Keys.Up) Then
                        empty = New Size(0, -5)
                    ElseIf (e.KeyCode = Keys.Down) Then
                        empty = New Size(0, 5)
                    End If
                    Dim activity As Activity
                    For Each activity In list
                        Dim designer As ActivityDesigner = ActivityDesigner.GetDesigner(activity)
                        If (Not designer Is Nothing) Then
                            MyBase.ParentView.InvalidateClientRectangle(New Rectangle(designer.Location, designer.Size))
                            designer.Location = (designer.Location + empty)
                            MyBase.ParentView.InvalidateClientRectangle(New Rectangle(designer.Location, designer.Size))
                        End If
                    Next
                    MyBase.PerformLayout
                    e.Handled = True
                ElseIf (e.KeyCode = Keys.Delete) Then
                    Dim obj3 As Object
                    For Each obj3 In service.GetSelectedComponents
                        Dim info As ConnectorHitTestInfo = [TryCast](obj3,ConnectorHitTestInfo)
                        If (Not info Is Nothing) Then
                            Dim associatedDesigner As FreeformActivityDesigner = [TryCast](info.AssociatedDesigner,FreeformActivityDesigner)
                            If (Not associatedDesigner Is Nothing) Then
                                Dim connectors As ReadOnlyCollection([Of] Connector) = associatedDesigner.Connectors
                                Dim num As Integer = info.MapToIndex
                                If (num < connectors.Count) Then
                                    service.SetSelectedComponents(New Object() { info }, SelectionTypes.Remove)
                                    associatedDesigner.RemoveConnector(connectors.Item(num))
                                    Dim obj4 As Object = associatedDesigner
                                    If (connectors.Count > 0) Then
                                        obj4 = New ConnectorHitTestInfo(associatedDesigner, (HitTestLocations.Connector Or HitTestLocations.Designer), If((num > 0), (num - 1), num))
                                    End If
                                    service.SetSelectedComponents(New Object() { obj4 }, SelectionTypes.Replace)
                                End If
                            End If
                        End If
                    Next
                    e.Handled = True
                End If
                If Not e.Handled Then
                    MyBase.OnKeyDown(e)
                End If
            End If
        End Sub

        Protected Overrides Sub OnLayoutPosition(ByVal e As ActivityDesignerLayoutEventArgs)
            MyBase.OnLayoutPosition(e)
            If Me.AutoSize Then
                Dim location As Point = Me.Location
                Dim enclosingRectangle As Rectangle = Me.GetEnclosingRectangle
                If Not enclosingRectangle.IsEmpty Then
                    If (Me.AutoSizeMode = AutoSizeMode.GrowOnly) Then
                        location.X = Math.Min(location.X, enclosingRectangle.Left)
                        location.Y = Math.Min(location.Y, enclosingRectangle.Top)
                    Else
                        location = enclosingRectangle.Location
                    End If
                End If
                Me.retainContainedDesignerLocations = True
                Me.Location = location
                Me.retainContainedDesignerLocations = False
            End If
            Dim connector As Connector
            For Each connector In Me.connectors
                connector.OnLayout(e)
            Next
        End Sub

        Protected Overrides Function OnLayoutSize(ByVal e As ActivityDesignerLayoutEventArgs) As Size
            Dim bounds As Rectangle = MyBase.Bounds
            Dim size As Size = bounds.Size
            MyBase.OnLayoutSize(e)
            If Not Me.AutoSize Then
                Return size
            End If
            If (Me.AutoSizeMode = AutoSizeMode.GrowOnly) Then
                Dim enclosingRectangle As Rectangle = Me.GetEnclosingRectangle
                If Not enclosingRectangle.IsEmpty Then
                    size.Width = (size.Width + Math.Max((bounds.Left - enclosingRectangle.Left), 0))
                    size.Width = (size.Width + Math.Max((enclosingRectangle.Right - bounds.Right), 0))
                    size.Height = (size.Height + Math.Max((bounds.Top - enclosingRectangle.Top), 0))
                    size.Height = (size.Height + Math.Max((enclosingRectangle.Bottom - bounds.Bottom), 0))
                End If
                Return size
            End If
            Return Me.MinimumSize
        End Function

        Friend Overrides Sub OnPaintContainedDesigners(ByVal e As ActivityDesignerPaintEventArgs)
            If Me.ShowConnectorsInForeground Then
                MyBase.OnPaintContainedDesigners(e)
            End If
            Dim connectorContainer As FreeformActivityDesigner = ConnectionManager.GetConnectorContainer(Me)
            If (((Not connectorContainer Is Nothing) AndAlso (Not MyBase.Activity Is Nothing)) AndAlso (Not MyBase.Activity.Site Is Nothing)) Then
                Dim region As Region = Nothing
                Dim clip As Region = e.Graphics.Clip
                Try 
                    If (Not clip Is Nothing) Then
                        [region] = New Region(connectorContainer.Bounds)
                        [region].Intersect(e.ViewPort)
                        e.Graphics.Clip = [region]
                    End If
                    Dim connector As Connector
                    For Each connector In connectorContainer.Connectors
                        If (Me Is connector.RenderingOwner) Then
                            connector.OnPaint(e)
                        End If
                    Next
                Finally
                    If (Not clip Is Nothing) Then
                        e.Graphics.Clip = clip
                        [region].Dispose
                    End If
                End Try
            End If
            If Not Me.ShowConnectorsInForeground Then
                MyBase.OnPaintContainedDesigners(e)
            End If
        End Sub

        Protected Overrides Sub OnResizing(ByVal e As ActivityDesignerResizeEventArgs)
            If Me.AutoSize Then
                If (Me.AutoSizeMode = AutoSizeMode.GrowOnly) Then
                    Dim enclosingRectangle As Rectangle = Me.GetEnclosingRectangle
                    If Not enclosingRectangle.IsEmpty Then
                        Dim empty As Rectangle = Rectangle.Empty
                        empty.X = Math.Min(enclosingRectangle.Left, e.Bounds.Left)
                        empty.Y = Math.Min(enclosingRectangle.Top, e.Bounds.Top)
                        empty.Width = Math.Max(CInt((enclosingRectangle.Right - empty.Left)), CInt((e.Bounds.Right - empty.Left)))
                        empty.Height = Math.Max(CInt((enclosingRectangle.Bottom - empty.Top)), CInt((e.Bounds.Bottom - empty.Top)))
                        If (empty <> e.Bounds) Then
                            e = New ActivityDesignerResizeEventArgs(e.SizingEdge, empty)
                        End If
                    End If
                Else
                    MyBase.PerformLayout
                End If
            End If
            Me.retainContainedDesignerLocations = True
            MyBase.OnResizing(e)
            Me.retainContainedDesignerLocations = False
        End Sub

        Protected Overrides Sub OnThemeChange(ByVal newTheme As ActivityDesignerTheme)
            MyBase.OnThemeChange(newTheme)
            If WorkflowTheme.CurrentTheme.AmbientTheme.ShowGrid Then
                Dim designer As ActivityDesigner
                For Each designer In Me.ContainedDesigners
                    designer.Location = DesignerHelpers.SnapToGrid(designer.Location)
                Next
                MyBase.PerformLayout
            End If
        End Sub

        Public Sub RemoveConnector(ByVal connector As Connector)
            If (connector Is Nothing) Then
                Throw New ArgumentNullException("connector")
            End If
            If Me.connectors.Contains(connector) Then
                Me.OnConnectorRemoved(New ConnectorEventArgs(connector))
                connector.SetParent(Nothing)
                Me.connectors.Remove(connector)
            End If
        End Sub

        Public Sub ResizeContainedDesigner(ByVal containedDesigner As ActivityDesigner, ByVal newSize As Size)
            If (containedDesigner Is Nothing) Then
                Throw New ArgumentNullException("containedDesigner")
            End If
            If Not Me.ContainedDesigners.Contains(containedDesigner) Then
                Throw New ArgumentException(DR.GetString("InvalidDesignerSpecified", New Object() { "containedDesigner" }))
            End If
            FreeformActivityDesigner.SetDesignerBounds(containedDesigner, New Rectangle(containedDesigner.Location, newSize))
            MyBase.PerformLayout
        End Sub

        Public Sub SendToBack(ByVal containedDesigner As ActivityDesigner)
            If (containedDesigner Is Nothing) Then
                Throw New ArgumentNullException("containedDesigner")
            End If
            If Not Me.ContainedDesigners.Contains(containedDesigner) Then
                Throw New ArgumentException(DR.GetString("InvalidDesignerSpecified", New Object() { "containedDesigner" }))
            End If
            Me.UpdateZOrder(containedDesigner, ZOrder.Background)
        End Sub

        Friend Shared Sub SetDesignerBounds(ByVal designer As ActivityDesigner, ByVal bounds As Rectangle)
            If (((Not designer Is Nothing) AndAlso (Not designer.Activity Is Nothing)) AndAlso (Not designer.Activity.Site Is Nothing)) Then
                Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(designer)
                Dim descriptor As PropertyDescriptor = If((Not properties Is Nothing), properties.Item("Size"), Nothing)
                If (Not descriptor Is Nothing) Then
                    descriptor.SetValue(designer.Activity, bounds.Size)
                Else
                    designer.Size = bounds.Size
                End If
                Dim descriptor2 As PropertyDescriptor = If((Not properties Is Nothing), properties.Item("Location"), Nothing)
                If (Not descriptor2 Is Nothing) Then
                    descriptor2.SetValue(designer.Activity, bounds.Location)
                Else
                    designer.Location = bounds.Location
                End If
                Dim service As WorkflowView = [TryCast](designer.Activity.Site.GetService(GetType(WorkflowView)),WorkflowView)
                If (Not service Is Nothing) Then
                    If (Not designer.ParentDesigner Is Nothing) Then
                        service.InvalidateLogicalRectangle(designer.ParentDesigner.Bounds)
                    Else
                        service.Invalidate
                    End If
                End If
            End If
        End Sub

        Private Sub UpdateZOrder(ByVal activityDesigner As ActivityDesigner, ByVal zorder As ZOrder)
            Dim service As IDesignerHost = [TryCast](MyBase.GetService(GetType(IDesignerHost)),IDesignerHost)
            Dim transaction As DesignerTransaction = Nothing
            If (Not service Is Nothing) Then
                transaction = service.CreateTransaction(DR.GetString("ZOrderUndoDescription", New Object() { activityDesigner.Text }))
            End If
            Try 
                Dim flag As Boolean = False
                Dim parentDesigner As CompositeActivityDesigner = Me
                Dim designer2 As ActivityDesigner = activityDesigner
                Do While ((Not parentDesigner Is Nothing) AndAlso (Not designer2 Is Nothing))
                    If TypeOf parentDesigner Is FreeformActivityDesigner Then
                        Dim containedDesigners As ReadOnlyCollection([Of] ActivityDesigner) = parentDesigner.ContainedDesigners
                        If ((containedDesigners.Count > 1) AndAlso (Not containedDesigners.Item(If((zorder = ZOrder.Background), 0, (containedDesigners.Count - 1))) Is designer2)) Then
                            Dim connector As Integer = If((zorder = ZOrder.Background), 0, containedDesigners.Count)
                            parentDesigner.MoveActivities(New ConnectorHitTestInfo(Me, HitTestLocations.Designer, connector), New List([Of] Activity)(New Activity() { designer2.Activity }).AsReadOnly)
                            flag = True
                        End If
                    End If
                    designer2 = parentDesigner
                    parentDesigner = parentDesigner.ParentDesigner
                Loop
                If flag Then
                    MyBase.Invalidate
                End If
                If (Not transaction Is Nothing) Then
                    transaction.Commit
                End If
            Catch exception As Exception
                If (Not transaction Is Nothing) Then
                    transaction.Cancel
                End If
                Throw exception
            End Try
        End Sub


        ' Properties
        Public Overrides ReadOnly Property AccessibilityObject As AccessibleObject
            Get
                If (Me.accessibilityObject Is Nothing) Then
                    Me.accessibilityObject = New FreeformDesignerAccessibleObject(Me)
                End If
                Return Me.accessibilityObject
            End Get
        End Property

        <DefaultValue(True)> _
        Public Property AutoSize As Boolean
            Get
                Return Me.autoSize
            End Get
            Set(ByVal value As Boolean)
                If (Me.autoSize <> value) Then
                    Me.autoSize = value
                    MyBase.PerformLayout
                End If
            End Set
        End Property

        Public Property AutoSizeMargin As Size
            Get
                Dim autoSizeMargin As Size = Me.autoSizeMargin
                If WorkflowTheme.CurrentTheme.AmbientTheme.ShowGrid Then
                    Dim gridSize As Size = WorkflowTheme.CurrentTheme.AmbientTheme.GridSize
                    autoSizeMargin.Width = (autoSizeMargin.Width + (gridSize.Width / 2))
                    autoSizeMargin.Height = (autoSizeMargin.Height + (gridSize.Height / 2))
                End If
                Return autoSizeMargin
            End Get
            Set(ByVal value As Size)
                If (Me.autoSizeMargin <> value) Then
                    Me.autoSizeMargin = value
                    MyBase.PerformLayout
                End If
            End Set
        End Property

        <DefaultValue(1)> _
        Public Property AutoSizeMode As AutoSizeMode
            Get
                Return Me.autoSizeMode
            End Get
            Set(ByVal value As AutoSizeMode)
                If (Me.autoSizeMode <> value) Then
                    Me.autoSizeMode = value
                    MyBase.PerformLayout
                End If
            End Set
        End Property

        Public Overrides ReadOnly Property CanExpandCollapse As Boolean
            Get
                Return False
            End Get
        End Property

        Public ReadOnly Property Connectors As ReadOnlyCollection([Of] Connector)
            Get
                Return Me.connectors.AsReadOnly
            End Get
        End Property

        <EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> _
        Friend ReadOnly Property DesignerConnectors As List([Of] Connector)
            Get
                Return New List([Of] Connector)(Me.connectors)
            End Get
        End Property

        <DefaultValue(True)> _
        Public Property EnableUserDrawnConnectors As Boolean
            Get
                Return (Me.enableUserDrawnConnectors AndAlso MyBase.IsEditable)
            End Get
            Set(ByVal value As Boolean)
                Me.enableUserDrawnConnectors = value
            End Set
        End Property

        Protected Friend Overrides ReadOnly Property EnableVisualResizing As Boolean
            Get
                If (Me.AutoSize AndAlso (Me.AutoSizeMode = AutoSizeMode.GrowAndShrink)) Then
                    Return False
                End If
                Return True
            End Get
        End Property

        Public Overrides ReadOnly Property FirstSelectableObject As Object
            Get
                Dim containedDesigners As IList([Of] ActivityDesigner) = Me.ContainedDesigners
                If (containedDesigners.Count <= 0) Then
                    Return Nothing
                End If
                Return containedDesigners.Item(0).Activity
            End Get
        End Property

        Protected Friend Overrides ReadOnly Property Glyphs As ActivityDesignerGlyphCollection
            Get
                Dim glyphs As New ActivityDesignerGlyphCollection
                glyphs.AddRange(MyBase.Glyphs)
                Dim service As ISelectionService = [TryCast](MyBase.GetService(GetType(ISelectionService)),ISelectionService)
                If (Not service Is Nothing) Then
                    Dim obj2 As Object
                    For Each obj2 In service.GetSelectedComponents
                        Dim info As ConnectorHitTestInfo = [TryCast](obj2,ConnectorHitTestInfo)
                        If ((Not info Is Nothing) AndAlso (info.AssociatedDesigner Is Me)) Then
                            glyphs.Add(New FreeFormConnectorSelectionGlyph(info.MapToIndex, (info Is service.PrimarySelection)))
                        End If
                    Next
                End If
                Return glyphs
            End Get
        End Property

        Public Overrides ReadOnly Property LastSelectableObject As Object
            Get
                Dim containedDesigners As IList([Of] ActivityDesigner) = Me.ContainedDesigners
                If (containedDesigners.Count <= 0) Then
                    Return Nothing
                End If
                Return containedDesigners.Item((containedDesigners.Count - 1)).Activity
            End Get
        End Property

        Public Overrides Property Location As Point
            Get
                Return MyBase.Location
            End Get
            Set(ByVal value As Point)
                If (Me.Location <> value) Then
                    Dim containedDesigners As ReadOnlyCollection([Of] ActivityDesigner) = Me.ContainedDesigners
                    Dim list As New List([Of] Point)
                    If Me.retainContainedDesignerLocations Then
                        Dim designer As ActivityDesigner
                        For Each designer In containedDesigners
                            list.Add(designer.Location)
                        Next
                    Else
                        Dim size As New Size((value.X - MyBase.Location.X), (value.Y - MyBase.Location.Y))
                        Dim parentDesigner As FreeformActivityDesigner = Me
                        Dim collection As New Collection([Of] Connector)
                        Do While (Not parentDesigner Is Nothing)
                            Dim connector As Connector
                            For Each connector In parentDesigner.Connectors
                                If (connector.RenderingOwner Is Me) Then
                                    collection.Add(connector)
                                End If
                            Next
                            parentDesigner = [TryCast](parentDesigner.ParentDesigner,FreeformActivityDesigner)
                        Loop
                        Dim connector2 As Connector
                        For Each connector2 In collection
                            connector2.Offset(size)
                        Next
                    End If
                    MyBase.Location = value
                    If (Me.retainContainedDesignerLocations AndAlso (containedDesigners.Count = list.Count)) Then
                        Dim i As Integer
                        For i = 0 To containedDesigners.Count - 1
                            containedDesigners.Item(i).Location = list.Item(i)
                        Next i
                    End If
                    MyBase.Invalidate
                End If
            End Set
        End Property

        Public Overrides ReadOnly Property MinimumSize As Size
            Get
                Dim minimumSize As Size = MyBase.MinimumSize
                If (((Not MyBase.Activity Is Nothing) AndAlso (Not MyBase.Activity.Site Is Nothing)) AndAlso Not TypeOf MyBase.ParentDesigner Is FreeformActivityDesigner) Then
                    minimumSize.Width = (minimumSize.Width * 4)
                    minimumSize.Height = (minimumSize.Height * 4)
                End If
                If (MyBase.IsRootDesigner AndAlso (Me.InvokingDesigner Is Nothing)) Then
                    Dim parentView As WorkflowView = MyBase.ParentView
                    minimumSize.Width = Math.Max(minimumSize.Width, (parentView.ViewPortSize.Width - (2 * DefaultWorkflowLayout.Separator.Width)))
                    minimumSize.Height = Math.Max(minimumSize.Height, (parentView.ViewPortSize.Height - (2 * DefaultWorkflowLayout.Separator.Height)))
                End If
                If Me.AutoSize Then
                    Dim enclosingRectangle As Rectangle = Me.GetEnclosingRectangle
                    If Not enclosingRectangle.IsEmpty Then
                        minimumSize.Width = Math.Max(minimumSize.Width, enclosingRectangle.Width)
                        minimumSize.Height = Math.Max(minimumSize.Height, enclosingRectangle.Height)
                    End If
                End If
                Return minimumSize
            End Get
        End Property

        Private ReadOnly Property MovingActivities As List([Of] ActivityDesigner)
            Get
                If (Me.movedActivities Is Nothing) Then
                    Me.movedActivities = New List([Of] ActivityDesigner)
                End If
                Return Me.movedActivities
            End Get
        End Property

        Protected Overridable ReadOnly Property ShowConnectorsInForeground As Boolean
            Get
                Return False
            End Get
        End Property

        Friend Overrides ReadOnly Property SupportedLayout As WorkflowLayout
            Get
                Return New WorkflowRootLayout(MyBase.Activity.Site)
            End Get
        End Property


        ' Fields
        Private accessibilityObject As FreeformDesignerAccessibleObject
        Private autoSize As Boolean = True
        Private autoSizeMargin As Size = FreeformActivityDesigner.DefaultAutoSizeMargin
        Private autoSizeMode As AutoSizeMode = AutoSizeMode.GrowOnly
        Private connectors As List([Of] Connector) = New List([Of] Connector)
        Friend Shared DefaultAutoSizeMargin As Size = New Size(40, 40)
        Private enableUserDrawnConnectors As Boolean = True
        Private movedActivities As List([Of] ActivityDesigner)
        Private retainContainedDesignerLocations As Boolean

        ' Nested Types
        Private NotInheritable Class FreeFormConnectorSelectionGlyph
            Inherits ConnectorSelectionGlyph
            ' Methods
            Friend Sub New(ByVal connectorIndex As Integer, ByVal isPrimarySelectionGlyph As Boolean)
                MyBase.New(connectorIndex, isPrimarySelectionGlyph)
            End Sub

            Public Overrides Function GetBounds(ByVal designer As ActivityDesigner, ByVal activated As Boolean) As Rectangle
                Return Rectangle.Empty
            End Function

            Protected Overrides Sub OnPaint(ByVal graphics As Graphics, ByVal activated As Boolean, ByVal ambientTheme As AmbientTheme, ByVal designer As ActivityDesigner)
            End Sub


            ' Properties
            Public Overrides ReadOnly Property IsPrimarySelection As Boolean
                Get
                    Return MyBase.isPrimarySelectionGlyph
                End Get
            End Property

        End Class

        Friend Class FreeformDesignerAccessibleObject
            Inherits CompositeDesignerAccessibleObject
            ' Methods
            Public Sub New(ByVal activityDesigner As FreeformActivityDesigner)
                MyBase.New(activityDesigner)
            End Sub

            Public Overrides Function GetChild(ByVal index As Integer) As AccessibleObject
                Dim activityDesigner As FreeformActivityDesigner = DirectCast(MyBase.ActivityDesigner, FreeformActivityDesigner)
                If activityDesigner.ShowConnectorsInForeground Then
                    Dim num As Integer = activityDesigner.Connectors.Count
                    If (index < num) Then
                        Return activityDesigner.Connectors.Item(index).AccessibilityObject
                    End If
                    Return activityDesigner.ContainedDesigners.Item((index - num)).AccessibilityObject
                End If
                Dim count As Integer = activityDesigner.ContainedDesigners.Count
                If (index < count) Then
                    Return activityDesigner.ContainedDesigners.Item(index).AccessibilityObject
                End If
                Return activityDesigner.Connectors.Item((index - count)).AccessibilityObject
            End Function

            Public Overrides Function GetChildCount() As Integer
                Dim activityDesigner As FreeformActivityDesigner = DirectCast(MyBase.ActivityDesigner, FreeformActivityDesigner)
                Return (MyBase.GetChildCount + activityDesigner.Connectors.Count)
            End Function

        End Class

        <ProvideProperty("Size", GetType(Activity)), ProvideProperty("Location", GetType(Activity))> _
        Private NotInheritable Class FreeFormDesignerPropertyExtender
            Implements IExtenderProvider
            ' Methods
            <MergableProperty(False), Browsable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DesignOnly(True)> _
            Public Function GetLocation(ByVal activity As Activity) As Point
                Dim empty As Point = Point.Empty
                Dim designer As ActivityDesigner = ActivityDesigner.GetDesigner(activity)
                If (Not designer Is Nothing) Then
                    empty = designer.Location
                End If
                Return empty
            End Function

            <DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(False), MergableProperty(False), DesignOnly(True)> _
            Public Function GetSize(ByVal activity As Activity) As Size
                Dim empty As Size = Size.Empty
                Dim designer As ActivityDesigner = ActivityDesigner.GetDesigner(activity)
                If (Not designer Is Nothing) Then
                    empty = designer.Size
                End If
                Return empty
            End Function

            Public Sub SetLocation(ByVal activity As Activity, ByVal location As Point)
                Dim designer As ActivityDesigner = ActivityDesigner.GetDesigner(activity)
                If (Not designer Is Nothing) Then
                    Dim designer2 As FreeformActivityDesigner = If((Not designer.ParentDesigner Is Nothing), [TryCast](designer.ParentDesigner,FreeformActivityDesigner), [TryCast](designer,FreeformActivityDesigner))
                    If (Not designer2 Is Nothing) Then
                        designer.Location = location
                        If designer2.AutoSize Then
                            designer2.PerformLayout
                        End If
                    End If
                End If
            End Sub

            Public Sub SetSize(ByVal activity As Activity, ByVal size As Size)
                Dim designer As ActivityDesigner = ActivityDesigner.GetDesigner(activity)
                If (Not designer Is Nothing) Then
                    Dim designer2 As FreeformActivityDesigner = If((Not designer.ParentDesigner Is Nothing), [TryCast](designer.ParentDesigner,FreeformActivityDesigner), [TryCast](designer,FreeformActivityDesigner))
                    If (Not designer2 Is Nothing) Then
                        designer.Size = size
                        If designer2.AutoSize Then
                            designer2.PerformLayout
                        End If
                    End If
                End If
            End Sub

            Private Function System.ComponentModel.IExtenderProvider.CanExtend(ByVal extendee As Object) As Boolean Implements IExtenderProvider.CanExtend
                Dim flag As Boolean = False
                Dim activity As Activity = [TryCast](extendee,Activity)
                If (Not activity Is Nothing) Then
                    Dim designer As ActivityDesigner = ActivityDesigner.GetDesigner(activity)
                    If ((Not designer Is Nothing) AndAlso (Not If((Not designer.ParentDesigner Is Nothing), [TryCast](designer.ParentDesigner,FreeformActivityDesigner), [TryCast](designer,FreeformActivityDesigner)) Is Nothing)) Then
                        flag = True
                    End If
                End If
                Return flag
            End Function

        End Class
    End Class
End Namespace

